package model

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	. "leaf/common"
	"leaf/core/db"
	"leaf/core/log"
	"leaf/core/tool"
	"leaf/pb"
)

func GetMongo() *mongo.Client {
	return db.GetMongo()
}

/*
 */
//func Init() {
//	db.InitMongo(conf.Config.MongoAddr)
//}

/*
 */
func InserOneDbAccount(dbAccount *pb.DbAccount) (string, error) {
	if dbAccount == nil {
		return "", Error_AccountExist
	}
	collection := db.GetMongo().Database("game").Collection("account")
	res, err := collection.InsertOne(context.TODO(), dbAccount)
	if tool.MongoError(err) {
		log.Release("RegisterHandler err:%v", Error_AccountExist)
		return "", Error_AccountExist
	}
	return res.InsertedID.(primitive.ObjectID).Hex(), nil
}

/*
 */
func FindDbAccount(name string) *pb.DbAccount {
	var dbAccount = &pb.DbAccount{}
	if cur, _ := db.GetMongo().Database("game").Collection("account").Find(context.TODO(), bson.M{"account": name}); cur.Next(context.TODO()) {
		cur.Decode(dbAccount)
		return dbAccount
	}
	return nil
}

/*
 */
func FindUserByAccountId(acid string) *pb.DbUser {
	if acid == "" {
		return nil
	}
	var dbUser = &pb.DbUser{}
	if cur, _ := db.GetMongo().Database("game").Collection("user").Find(context.TODO(), bson.M{"accountid": acid}); cur.Next(context.TODO()) {
		cur.Decode(dbUser)
		return dbUser
	}
	return nil
}

/*
 */
func IsUserNameRepeated(name string) bool {
	if name == "" {
		return true
	}
	if cur, _ := db.GetMongo().Database("game").Collection("user").Find(context.TODO(), bson.M{"name": name}); cur.Next(context.TODO()) {
		return true
	}
	return false
}
